package gdut.stream.middle;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;

public class FlatMapTest {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        ArrayList<String> books = new ArrayList<>();
        books.add("数学");
        books.add("英语");
        books.add("语文");
        for (int i = 0; i < 5; i++) {
            Student student = new Student(i, "student" + i, books);
            students.add(student);
        }
        Stream<Student> studentStream1 = students.stream();
        Stream<Student> studentStream2 = students.stream();
//        使用map
        studentStream1
                .map(new Function<Student, List<String>>() {
                    @Override
                    public List<String> apply(Student student) {
                        return student.getBooks();
                    }
                })
                .forEach(new Consumer<List<String>>() {
                    @Override
                    public void accept(List<String> strings) {
                        System.out.println(strings);
                    }
                });
//        使用flatMap
        studentStream2
                .flatMap(new Function<Student, Stream<String>>() {
                    @Override
                    public Stream<String> apply(Student student) {
                        return student.getBooks().stream();
                    }
                })
                .distinct()
                .forEach(new Consumer<String>() {
                    @Override
                    public void accept(String s) {
                        System.out.println(s);
                    }
                });

    }
}
